<template>
  <div class="app-container">
    <!-- 头部区域 -->
    <div class="app-header">
      <div class="header-left">
        <div class="logo" @click="handleLogoClick">
          <h1>环境管理平台</h1>
        </div>
      </div>
      
      <div class="header-right">
        <div class="admin-status" v-if="authState.isAdmin">
          <a-tag color="green">管理员模式</a-tag>
          <a-button type="link" @click="logout">退出登录</a-button>
        </div>
        
        <a-button 
          type="primary" 
          @click="refreshData"
          :loading="loading"
          :icon="h(ReloadOutlined)"
        >
          刷新
        </a-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="filter-container">
        <div class="search-wrapper">
          <a-input-search
            v-model:value="filterState.searchKeyword"
            placeholder="搜索项目名称或域名..."
            @search="onSearch"
            @input="onSearchInput"
            size="large"
            class="search-input"
          />
        </div>
        
        <div class="select-wrapper">
          <a-select
            v-model:value="filterState.selectedGroupIds"
            mode="multiple"
            placeholder="选择项目分组"
            size="large"
            class="group-select"
            @change="onGroupFilter"
          >
            <a-select-option 
              v-for="group in groups" 
              :key="group.id" 
              :value="group.id"
            >
              {{ group.name }}
            </a-select-option>
          </a-select>
        </div>
        
        <div class="buttons-wrapper">
          <a-button 
            v-if="authState.isAdmin"
            type="dashed" 
            size="large"
            @click="showCreateGroup"
            :icon="h(PlusOutlined)"
            title="创建新分组"
            class="action-button"
          >
            添加分组
          </a-button>
          
          <a-button 
            v-if="authState.isAdmin"
            type="default" 
            size="large"
            @click="showGroupManagement"
            :icon="h(SettingOutlined)"
            title="管理分组"
            class="action-button manage-button"
          >
            管理分组
          </a-button>
          
          <a-button 
            v-if="authState.isAdmin"
            type="primary" 
            size="large"
            @click="showCreateProject"
            :icon="h(PlusOutlined)"
            class="action-button"
          >
            新建项目
          </a-button>
        </div>
      </div>
    </div>

    <!-- 项目列表区域 -->
    <div class="projects-section">
      <a-spin :spinning="loading">
        <div v-if="filteredProjects.length === 0" class="empty-state">
          <a-empty 
            :description="hasSearchFilter ? '没有找到匹配的项目' : '暂无项目数据'"
          >
            <a-button 
              v-if="authState.isAdmin && !hasSearchFilter"
              type="primary" 
              @click="showCreateProject"
            >
              创建第一个项目
            </a-button>
          </a-empty>
        </div>
        
        <div v-else class="projects-grid">
          <div v-for="project in filteredProjects" :key="project.id" class="project-item">
            <ProjectCard
              :project="project"
              :is-admin="authState.isAdmin"
              @edit="onEditProject"
              @delete="onDeleteProject(project.id)"
              @refresh="refreshData"
              @environmentChange="onEnvironmentChange"
            />
          </div>
        </div>
      </a-spin>
    </div>

    <!-- 项目表单弹窗 -->
    <ProjectForm
      v-model:visible="projectFormVisible"
      :groups="groups"
      :edit-project="editingProject"
      @success="onProjectFormSuccess"
    />

    <!-- 创建分组弹窗 -->
    <a-modal
      v-model:open="groupFormVisible"
      title="创建新分组"
      :footer="null"
      width="400px"
    >
      <a-form
        ref="groupFormRef"
        :model="groupForm"
        layout="vertical"
        @finish="onGroupFormSuccess"
      >
        <a-form-item
          label="分组名称"
          name="name"
          :rules="[{ required: true, message: '请输入分组名称' }]"
        >
          <a-input v-model:value="groupForm.name" placeholder="请输入分组名称" />
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit"
            :loading="groupLoading"
            style="width: 100%"
          >
            创建分组
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分组管理弹窗 -->
    <a-modal
      v-model:open="groupManagementVisible"
      title="分组管理"
      :footer="null"
      width="600px"
    >
      <div class="group-management-container">
        <!-- 分组列表区域 -->
        <div class="groups-list-section">
          <h4>现有分组 ({{ groups.length }}个)</h4>
          <div class="groups-list">
            <div 
              v-for="group in groups" 
              :key="group.id" 
              class="group-item"
            >
              <div class="group-info">
                <div class="group-name">{{ group.name }}</div>
                <div class="group-meta">
                  <span class="project-count">
                    {{ getProjectCountInGroup(group.id) }} 个项目
                  </span>
                  <span class="created-time">
                    创建于 {{ formatDate(group.createdAt) }}
                  </span>
                </div>
              </div>
              
              <div class="group-actions">
                <a-button 
                  type="text" 
                  size="small"
                  @click="showEditGroup(group)"
                  :icon="h(EditOutlined)"
                  title="编辑分组"
                  class="edit-button"
                >
                  编辑
                </a-button>
                <a-button 
                  type="text" 
                  size="small"
                  danger
                  @click="showDeleteGroupConfirm(group)"
                  :icon="h(DeleteOutlined)"
                  :disabled="getProjectCountInGroup(group.id) > 0"
                  :title="getProjectCountInGroup(group.id) > 0 ? '分组下有项目，无法删除' : '删除分组'"
                  class="delete-button"
                >
                  删除
                </a-button>
              </div>
            </div>
            
            <div v-if="groups.length === 0" class="empty-groups">
              <a-empty description="暂无分组" />
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 编辑分组弹窗 -->
    <a-modal
      v-model:open="editGroupVisible"
      title="编辑分组"
      :footer="null"
      width="400px"
    >
      <a-form
        ref="editGroupFormRef"
        :model="editGroupForm"
        layout="vertical"
        @finish="onEditGroupSuccess"
      >
        <a-form-item
          label="分组名称"
          name="name"
          :rules="[{ required: true, message: '请输入分组名称' }]"
        >
          <a-input v-model:value="editGroupForm.name" placeholder="请输入分组名称" />
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit"
            :loading="editGroupLoading"
            style="width: 100%"
          >
            保存修改
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 登录弹窗 -->
    <a-modal
      v-model:open="loginModalVisible"
      title="管理员登录"
      :footer="null"
      width="400px"
    >
      <a-form
        ref="loginFormRef"
        :model="loginForm"
        layout="vertical"
        @finish="onLogin"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="loginForm.username" placeholder="用户名" />
        </a-form-item>
        
        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="loginForm.password" placeholder="密码" />
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit"
            :loading="loginLoading"
            style="width: 100%"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h, nextTick, watch } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ReloadOutlined, PlusOutlined, DeleteOutlined, SettingOutlined, EditOutlined } from '@ant-design/icons-vue';
import ProjectCard from '@/components/ProjectCard.vue';
import ProjectForm from '@/components/ProjectForm.vue';
import type { Project, ProjectGroup, FilterState, AuthState } from '@/types';
import { projectApi, groupApi } from '@/api';
import { authManager } from '@/utils/auth';
import { storageManager } from '@/utils/storage';

// 响应式数据
const loading = ref(false);
const loginLoading = ref(false);
const projects = ref<Project[]>([]);
const groups = ref<ProjectGroup[]>([]);

// 筛选状态
const filterState = reactive<FilterState>({
  searchKeyword: '',
  selectedGroupIds: [],
});

// 权限状态
const authState = reactive<AuthState>({
  isAdmin: false,
  loginClickCount: 0,
});

// 弹窗状态
const projectFormVisible = ref(false);
const groupFormVisible = ref(false);
const groupManagementVisible = ref(false);
const editGroupVisible = ref(false);
const loginModalVisible = ref(false);
const editingProject = ref<Project | null>(null);

// 分组表单
const groupFormRef = ref();
const groupForm = reactive({
  name: '',
});

// 编辑分组表单
const editGroupFormRef = ref();
const editGroupForm = reactive({
  name: '',
  id: '',
});

// 分组相关状态
const groupLoading = ref(false);
const editGroupLoading = ref(false);
const deleteGroupLoading = ref(false);

// 登录表单
const loginFormRef = ref();
const loginForm = reactive({
  username: '',
  password: '',
});

// 计算属性
const hasSearchFilter = computed(() => {
  return filterState.searchKeyword.trim() || filterState.selectedGroupIds.length > 0;
});

const filteredProjects = computed(() => {
  let result = [...projects.value];

  // 按关键词搜索
  if (filterState.searchKeyword.trim()) {
    const keyword = filterState.searchKeyword.toLowerCase();
    result = result.filter(project => {
      // 搜索项目名称
      if (project.name.toLowerCase().includes(keyword)) {
        return true;
      }
      
      // 搜索域名
      return project.environments.some(env => 
        env.hosts.some(host => host.toLowerCase().includes(keyword))
      );
    });
  }

  // 按分组筛选
  if (filterState.selectedGroupIds.length > 0) {
    result = result.filter(project => 
      filterState.selectedGroupIds.includes(project.groupId)
    );
  }

  return result;
});

const updateWhistleRule = async () => {
  const activeIds = storageManager.getActiveEnvironments();
  const environments = projects.value.map(project => project.environments).flat();
  const rules = environments.filter(env => activeIds.includes(env.id)).map(env => env.hosts).flat();
  await projectApi.updateRules(rules);
};

// 环境变化处理（配合互斥激活系统）
const onEnvironmentChange = async (envId: string, checked: boolean, envType: 'development'|'test'|'preview'|'production'|'custom') => {
  // 由于存储管理器已经处理了互斥逻辑，这里只需要同步UI状态
  
  // 1) 同步到页面本地状态（切换文案）
  const all = projects.value.flatMap(p => p.environments);
  const activeSet = new Set(storageManager.getActiveEnvironments());
  all.forEach(env => {
    env.isActive = activeSet.has(env.id);
  });

  // 2) 重新计算并下发规则
  await updateWhistleRule();
  
  // 3) 显示环境切换提示
  if (checked) {
    const envName = all.find(env => env.id === envId)?.name || '未知环境';
    const envTypeName = getEnvironmentTypeName(envType);
    const projectName = projects.value.find(p => 
      p.environments.some(env => env.id === envId)
    )?.name || '未知项目';
    message.success(`项目 "${projectName}" 的 ${envTypeName} "${envName}" 已激活`);
  }
  
  // 4) 强制更新所有 ProjectCard 组件的状态
  await nextTick();
  projects.value.forEach(project => {
    project.environments.forEach(env => {
      env.isActive = activeSet.has(env.id);
    });
  });
};

// 获取环境类型名称的辅助函数
const getEnvironmentTypeName = (envType: string): string => {
  const typeNames: Record<string, string> = {
    development: '开发环境',
    test: '测试环境',
    preview: '预发布环境',
    production: '正式环境',
    custom: '自定义环境',
  };
  return typeNames[envType] || '未知环境';
};

// 根据分组ID获取分组信息
const getGroupById = (groupId: string) => {
  return groups.value.find(group => group.id === groupId);
};

// 获取分组下的项目数量
const getProjectCountInGroup = (groupId: string) => {
  return projects.value.filter(project => project.groupId === groupId).length;
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  });
};

// 初始化数据
const initData = async () => {
  loading.value = true;
  
  try {
    await loadProjects()
    await updateWhistleRule()
  } catch (error: any) {
    message.error(error.message || '数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 加载项目数据
const loadProjects = async () => {
  try {
    const response = await projectApi.getAll();
    if (response.success && response.data) {
      projects.value = response.data.projects;
      groups.value = response.data.projectGroups;
      
      // 同步环境激活状态 - 确保数据加载后状态一致
      const activeIds = storageManager.getActiveEnvironments();
      
      // 验证项目级别的环境激活限制
      const projectActiveMap = new Map<string, string>();
      projects.value.forEach(project => {
        let activeCount = 0;
        let activeEnvId: string | null = null;
        
        project.environments.forEach(env => {
          if (activeIds.includes(env.id)) {
            activeCount++;
            activeEnvId = env.id;
          }
          env.isActive = activeIds.includes(env.id);
        });
        
        // 如果项目有多个活跃环境，只保留第一个，清除其他的
        if (activeCount > 1) {
          project.environments.forEach(env => {
            if (env.isActive && env.id !== activeEnvId) {
              env.isActive = false;
              const index = activeIds.indexOf(env.id);
              if (index > -1) {
                activeIds.splice(index, 1);
              }
            }
          });
          
          // 更新存储
          try {
            localStorage.setItem('env_manager_active_environments', JSON.stringify(activeIds));
          } catch (error) {
            console.error('更新活跃环境状态失败:', error);
          }
        }
        
        // 记录项目的活跃环境
        if (activeEnvId) {
          projectActiveMap.set(project.id, activeEnvId);
        }
      });
      
      // 更新项目活跃环境映射
      try {
        const projectEnvMap = Object.fromEntries(projectActiveMap);
        localStorage.setItem('env_manager_project_active_env', JSON.stringify(projectEnvMap));
      } catch (error) {
        console.error('更新项目活跃环境映射失败:', error);
      }
    }
  } catch (error: any) {
    console.error('加载项目失败:', error);
    throw error;
  }
};

// 刷新数据
const refreshData = async () => {
  await loadProjects();
  
  // 同步环境激活状态 - 修复刷新后状态不一致的问题
  const activeIds = storageManager.getActiveEnvironments();
  projects.value.forEach(project => {
    project.environments.forEach(env => {
      env.isActive = activeIds.includes(env.id);
    });
  });
  
  message.success('数据刷新成功');
};

// 显示创建分组弹窗
const showCreateGroup = () => {
  groupFormVisible.value = true;
  groupForm.name = '';
  nextTick(() => {
    groupFormRef.value?.clearValidate();
  });
};

// 显示分组管理弹窗
const showGroupManagement = () => {
  groupManagementVisible.value = true;
};

// 显示编辑分组弹窗
const showEditGroup = (group: ProjectGroup) => {
  editGroupForm.name = group.name;
  editGroupForm.id = group.id;
  editGroupVisible.value = true;
  nextTick(() => {
    editGroupFormRef.value?.clearValidate();
  });
};

// 分组表单提交成功
const onGroupFormSuccess = async (values: any) => {
  try {
    groupLoading.value = true;
    const response = await groupApi.create(values);
    if (response.success) {
      message.success('分组创建成功');
      groupFormVisible.value = false;
      await loadProjects(); // 重新加载数据
    } else {
      message.error(response.message || '分组创建失败');
    }
  } catch (error: any) {
    message.error(error.message || '分组创建失败');
  } finally {
    groupLoading.value = false;
  }
};

// 编辑分组表单提交成功
const onEditGroupSuccess = async (values: any) => {
  try {
    editGroupLoading.value = true;
    const response = await groupApi.update(editGroupForm.id, values);
    if (response.success) {
      message.success('分组修改成功');
      editGroupVisible.value = false;
      await loadProjects(); // 重新加载数据
    } else {
      message.error(response.message || '分组修改失败');
    }
  } catch (error: any) {
    message.error(error.message || '分组修改失败');
  } finally {
    editGroupLoading.value = false;
  }
};

// 显示删除分组确认对话框
const showDeleteGroupConfirm = (group: ProjectGroup) => {
  // 检查分组下是否有项目
  const projectsInGroup = projects.value.filter(project => project.groupId === group.id);
  
  if (projectsInGroup.length > 0) {
    message.warning(`分组 "${group.name}" 下还有 ${projectsInGroup.length} 个项目，无法删除`);
    return;
  }
  
  // 使用 Ant Design Vue 的 Modal.confirm
  Modal.confirm({
    title: '确认删除分组',
    content: `确定要删除分组 "${group.name}" 吗？此操作不可撤销。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: () => deleteGroup(group.id),
  });
};

// 删除分组
const deleteGroup = async (groupId: string) => {
  try {
    deleteGroupLoading.value = true;
    const response = await groupApi.delete(groupId);
    if (response.success) {
      message.success('分组删除成功');
      await loadProjects(); // 重新加载数据
      
      // 如果当前筛选中包含了被删除的分组，需要清除筛选
      const deletedGroupIndex = filterState.selectedGroupIds.indexOf(groupId);
      if (deletedGroupIndex > -1) {
        filterState.selectedGroupIds.splice(deletedGroupIndex, 1);
      }
    } else {
      message.error(response.message || '分组删除失败');
    }
  } catch (error: any) {
    message.error(error.message || '分组删除失败');
  } finally {
    deleteGroupLoading.value = false;
  }
};

// Logo点击处理
const handleLogoClick = () => {
  const shouldShowLogin = authManager.handleLogoClick();
  authState.loginClickCount = authManager.getLoginClickCount();
  
  if (shouldShowLogin) {
    loginModalVisible.value = true;
    // 重置登录表单
    loginForm.username = '';
    loginForm.password = '';
    nextTick(() => {
      loginFormRef.value?.clearValidate();
    });
  }
};

// 管理员登录
const onLogin = async () => {
  try {
    loginLoading.value = true;
    
    const success = authManager.login(loginForm.username, loginForm.password);
    if (success) {
      authState.isAdmin = true;
      loginModalVisible.value = false;
      message.success('登录成功');
    } else {
      message.error('用户名或密码错误');
    }
  } catch (error) {
    message.error('登录失败');
  } finally {
    loginLoading.value = false;
  }
};

// 退出登录
const logout = () => {
  authManager.logout();
  authState.isAdmin = false;
  message.success('已退出登录');
};

// 搜索处理
const onSearch = () => {
  saveFilterState();
};

const onSearchInput = () => {
  saveFilterState();
};

// 分组筛选处理
const onGroupFilter = () => {
  saveFilterState();
};

// 保存筛选状态
const saveFilterState = () => {
  storageManager.saveFilterState(filterState);
};

// 加载筛选状态
const loadFilterState = () => {
  const savedState = storageManager.getFilterState();
  Object.assign(filterState, savedState);
};

// 显示创建项目弹窗
const showCreateProject = () => {
  editingProject.value = null;
  projectFormVisible.value = true;
};

// 编辑项目
const onEditProject = (projectId: string) => {
  const project = projects.value.find(p => p.id === projectId);
  if (project) {
    editingProject.value = project;
    projectFormVisible.value = true;
  }
};

// 删除项目
const onDeleteProject = (projectId: string) => {
  projectApi.delete(projectId);
  refreshData();
};

// 项目表单操作成功
const onProjectFormSuccess = () => {
  refreshData();
};

// 监听筛选状态变化，自动保存
watch(filterState, () => {
  saveFilterState();
}, { deep: true });

// 组件挂载
onMounted(() => {
  // 加载权限状态
  authState.isAdmin = authManager.getIsAdmin();
  authState.loginClickCount = authManager.getLoginClickCount();
  
  // 加载筛选状态
  loadFilterState();
  
  // 初始化数据
  initData();
});
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 24px;
  padding-top: 0;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  cursor: pointer;
  user-select: none;
}

.logo h1 {
  margin: 0;
  color: #1890ff;
  font-size: 24px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.admin-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-filter-section {
  margin-bottom: 20px;
  margin-top: 20px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-container {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 12px;
}

.search-wrapper {
  flex: 0 0 40%;
}

.search-input {
  width: 100%;
}

.select-wrapper {
  flex: 0 0 30%;
}

.group-select {
  width: 100%;
}

.buttons-wrapper {
  flex: 0 0 auto;
  display: flex;
  gap: 16px;
  margin-left: 16px;
}

.action-button {
  min-width: 100px;
  padding: 0 16px;
}

.manage-button {
  min-width: 80px;
  padding: 0 12px;
}

.projects-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  min-height: 400px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  width: 100%;
}

.project-item {
  transition: transform 0.2s ease;
  margin-bottom: 20px;
  width: 100%;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.project-item:hover {
  transform: translateY(-2px);
}

/* 分组管理样式 */
.group-management-container {
  max-height: 500px;
  overflow-y: auto;
}



.groups-list-section h4 {
  margin: 0 0 16px 0;
  color: #555;
}

.groups-list {
  max-height: 300px;
  overflow-y: auto;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #fff;
  transition: all 0.2s ease;
}

.group-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.1);
}

.group-info {
  flex: 1;
}

.group-name {
  font-size: 16px;
  font-weight: 500;
  color: #555;
  margin-bottom: 4px;
}

.group-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #888;
}

.project-count {
  color: #1890ff;
  font-weight: 500;
}

.group-actions {
  display: flex;
  gap: 8px;
}

/* 编辑按钮样式优化 */
.edit-button {
  color: #52c41a !important;
  border-color: transparent !important;
}

.edit-button:hover {
  color: #73d13d !important;
  background-color: #f6ffed !important;
  border-color: #b7eb8f !important;
}

.edit-button .anticon {
  color: #52c41a !important;
}

.edit-button:hover .anticon {
  color: #73d13d !important;
}

/* 删除按钮样式优化 */
.delete-button {
  color: #ff7875 !important;
}

.delete-button:hover {
  color: #ff4d4f !important;
  background-color: #fff2f0 !important;
  border-color: #ffccc7 !important;
}

.delete-button:disabled {
  color: #d9d9d9 !important;
}

.delete-button .anticon {
  color: inherit !important;
}

.empty-groups {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }
  
  .app-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-right {
    justify-content: space-between;
  }
  
  .projects-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-wrapper,
  .select-wrapper {
    flex: 1 1 auto;
    margin-bottom: 12px;
    width: 100%;
  }
  
  .buttons-wrapper {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }
  
  .action-button {
    flex: 1;
    min-width: 0;
  }

  .group-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .group-actions {
    justify-content: flex-end;
  }
}
</style>
